import numpy as np
from scipy import *

import mc_functions as mcf

import pdb

import random
import shelve
import pickle
import time
import shutil
from datetime import datetime
import sys

class VCGeneration:

    #---------------- CONSTRUCTOR
    def __init__(self, Syn_exc_par,Syn_inh_par,Noise_par,Fr_par,Init_par,Sim_par):
         
         self.Syn_exc_par = Syn_exc_par
         self.Syn_inh_par = Syn_inh_par
         self.Noise_par = Noise_par
         self.Fr_par = Fr_par
         self.Init_par = Init_par
         self.Sim_par = Sim_par
         



 #---------------- reset values
   
    def reset(self,tstop='def'): # default time is the one indicated in the main
        dt=self.Sim_par['dt'];
        if tstop=='def':
            tstop=self.Sim_par['duration'];
        self.timevec=np.array(arange(0,tstop,dt)) # reset the time

        self.input_times=[]; #reset the input time
        self.input_amplitude=[]; #.. and amplitudes
        self.I=zeros(self.timevec.shape); # and current

    def run(self,tstop='def',rate='def'):
        if tstop=='def':
            tstop=self.Sim_par['duration'];
        if rate=='def':
            rate=self.Fr_par['e'];

        self.reset(tstop);

        spiketime=mcf.inhom_poisson(rate,self.timevec); # generate the timing of the poisson spikes

        if self.Syn_exc_par['WeightDist']=='LogNormal': # generate the amplitudes of each spike
            B_mu_e=log((self.Syn_exc_par['Bee']**2)/sqrt(self.Syn_exc_par['Beestd']**2+self.Syn_exc_par['Bee']**2));
            B_sigma_e=sqrt(log(self.Syn_exc_par['Beestd']**2/self.Syn_exc_par['Bee']**2 +1));
            amplitude=np.random.lognormal(B_mu_e,B_sigma_e,size(spiketime))           
        elif self.Syn_exc_par['WeightDist']=='Normal': # generate the amplitudes of each spike
            B_mu_e=self.Syn_exc_par['Bee'];
            B_sigma_e=self.Syn_exc_par['Beestd'];
            amplitude=np.random.normal(B_mu_e,B_sigma_e,size(spiketime))
        else:
            print 'ERROR, NOT AN ALLOWED DISTRIBUTION';

        


        return spiketime,amplitude
#---------------- save parameters
    def save_loop(self,filename='def',folder='def'):
        if filename=='def':
            filename=str(datetime.now())
        
        if folder=='def':
            folder='../datasave/'

        pathfile=folder+filename
        import scipy.io as io
        
        io.savemat(pathfile+'_loop',self.val_loop1D)
        
        shutil.copyfile('main_class.py',pathfile+'_source.py')



# -------------- FUNCTION USED BY THE CLASS

def meanstd2lognorm(a,b):
    aln=log((a**2)/(sqrt((b)**2 + a**2)))
    bln=sqrt(log((b)**2/(a**2)+1))

    return aln, bln
